/*
 * Creator:     ML
 * CreatDate:   2019-12-17
 * descripts：  房间类型和床位费类型关联
 * */
import React from 'react';
import { Form, Row, Col, Select, Button, Popconfirm, Table, message, Divider } from 'antd';
import { $http } from '../../containers/config/https';
import store from '../../store';
import BedCostToBedTypeModal from './component/BedCostToBedTypeModal';
import CommonPagination from 'components/pagination/index';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';

const FormItem = Form.Item;
const Option = Select.Option;
const paddRightCol = {
    paddingRight: "0px"
}
const formItemLayoutType = {
    labelCol: { span: 8 },
    wrapperCol: { span: 16 }
}
const formItemLayout = { // label 和input宽度
    labelCol: { span: 8 },
    wrapperCol: { span: 14 },
}

const BedCostToBedType = Form.create()(
    class BedCostToBedType extends React.Component {
        constructor(props) {
            super(props)
            this.state = {
                total: 0,//表格总数据
                bedData: [],//查询数据
                values: {},//查询条件数据
                searchLoading: false,//查询请求
                rowIds: '',//表格行选中 页面数据
                headerHeight: '',
                page: 1,
                pageSize: 10,
                size: 'small',
                search: '',
                totalWidth: 0
            }
        }

        componentDidMount() {
            let box = document.querySelector('.department-header');
            if (box) { //此处在加一层判断，更加严密，如果box存在的情况下获取
                this.setState({ headerHeight: box.offsetHeight })
            }
            this.getHopSelect()
            this.getFindDate()
            this.getMainTableColumns()
            this.getFeeType()
            this.getRoomType()
        }

        //动态表头
        onColumnRef = (ref) => {
            this.columnRef = ref;
        }

        // 获取主列表columns
        getMainTableColumns = () => {
            let data = {
                params: [{
                    compontName: 'RoomTypeAndBedFeeTypeAss',
                    reactCode: ['RoomTypeAndBedFeeTypeAss'],
                    type: 'C',
                }]
            }
            $http.post('urlS', this, {
                code: '01040073',
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        let arr = res.result && res.result.C.length > 0 ? JSON.parse(JSON.stringify(res.result.C)).map(item => {
                            return {
                                align: item.align,
                                widthNum: parseInt(item.width),
                                width: item.width,
                                dataIndex: item.dataIndex,
                                title: <div onDoubleClick={() => this.columnRef.onOpenModel()}>{item.title}</div>,
                                display: item.display,
                                key: item.seqNo,
                                // render: (text, record) => {
                                //    if (item.code == 'status') {
                                //      return (
                                //      <span>{record.status=='Y'?'生效':'失效'}</span>
                                //      )
                                //    }
                                //    return text
                                //  }
                            }
                        }) : '';
                        let filterArr = arr.filter(function (item) { return item.display === 'Y' });
                        let seqArr = {
                            align: 'center',
                            widthNum: 140,
                            width: '130px',
                            code: 'edit',
                            dataIndex: 'edit',
                            title: '操作',
                            display: 'Y',
                            render: (value, row, index) => {
                                return (
                                    <span>
                                        <a onClick={(e) => this.toggleEditable(row, '1')}>编辑</a>
                                        <Divider type="vertical" />
                                        <Popconfirm title="是否要删除此行" onConfirm={() => this.toggleEditable(row, '2')}>
                                            <a style={{ color: 'red' }} >删除</a>
                                        </Popconfirm>
                                    </span>
                                )
                            },
                        }
                        filterArr.push(seqArr)
                        this.setState({ columns: filterArr, totalWidth: res.totalWidth })
                    }
                }
            })
        }

        //获取医院下拉框
        getHopSelect = () => {
            let data = {
                params: [{
                    hospID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).hospID : '',
                    logonGroupID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).groupID : '',
                    logonHospID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).hospID : '',
                }],
            }
            $http.post('urlS', this, {
                code: '01040001',
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        this.setState({
                            hospArr: res.result
                        })
                    }
                }
            })
        }

        // 修改page和pageSize 跳转至---
        onChange = (e, pageSize) => {
            this.setState({ page: e, pageSize: this.state.pageSize }, () => {
                // 重新调用查询方法
                let { values } = this.state;
                this.getFindDate(values);
            })
        }

        //下拉选择页数
        onShowSizeChange = (page, pageSize) => {
            this.setState({ page: 1, pageSize: pageSize }, () => {
                // 重新调用查询方法
                let { values } = this.state;
                this.getFindDate(values, 'search');
            })
        }

        // 显示分页总条数
        showTotal(total) {
            return `共 ${total} 条`;
        }

        //定位到最新添加/当前修改的记录
        getNewData = (id) => {
            //跳至最后一页 并定位到刚添加的这条记录
            if (id) {
                let lastPage = Math.ceil((this.state.total + 1) / this.state.pageSize)
                this.onChange(lastPage, this.state.pageSize)
                this.setState({
                    rowIds: id
                })
            } else {
                this.onChange(this.state.page, this.state.pageSize)
            }
        }

        //获取查询数据
        getFindDate = (values, e) => {
            if (this.state.total == 0) {
                this.setState({
                    searchLoading: true
                })
            }
            let { page, pageSize, } = this.state;
            let data = {}
            data = {
                params: [{
                    userID: JSON.parse(sessionStorage.userData).userID || '',
                    logonGroupID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).groupID : '',
                    logonHospID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).hospID : '',
                    hospID: values && values.hospId || '',
                    roomTypeID: values && values.getRoom || '',
                    feeTypeID: values && values.getBed || '',
                }],
                pagination: [{
                    pageSize: pageSize,
                    currentPage: page,
                }]
            }
            $http.post('urlS', this, {
                code: '01040132',
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0 && res.result) {
                        this.setState({
                            searchLoading: false,
                            search: e
                        })
                        for (var i = 0; i < res.result.data.length; i++) {
                            res.result.data[i].key = i + 'bed'
                        }
                        this.setState({ bedData: res.result.data, total: res.result.TotalCount, }, () => {
                        })
                    } else {
                        this.setState({
                            searchLoading: false
                        })
                    }
                    //  if (res.result.data && res.result.data.length == 0 && res.result.totalCount > 0) {
                    //      let prevPage = this.state.page - 1
                    //      this.onChange(prevPage, this.state.pageSize)
                    //  }
                },
                error: function () {
                    this.setState({
                        searchLoading: false
                    })
                }
            })
        }

        //点击查询---
        findData = () => {
            this.props.form.validateFields((err, values) => {
                if (!err) {
                    this.setState({
                        values: values,
                        rowIds: ''
                    }, () => {
                        this.onShowSizeChange('1', this.state.pageSize)
                    })
                }
            })
        }

        // 调用子组件的连接事件 -- 添加新
        OnChildrefs = (ref) => {
            this.child = ref
        }

        add = () => {
            this.child.showModal()
        }

        //点击查询后 表格行
        setRowClassNames = (record) => {
            return record.ID === this.state.rowIds ? 'clickRowStyle' : '';
        }

        //点击Row
        onClickRow = (record) => {
            return {
                onClick: () => {
                    this.setState({
                        parms: record,
                    })
                    if (this.state.rowIds === '') {
                        this.setState({
                            rowIds: record.ID,
                        });
                    } else {
                        if (this.state.rowIds !== record.ID) {
                            this.setState({
                                rowIds: record.ID,
                            });
                        } else {
                            this.setState({
                                rowIds: '',
                                detailInfo: {},
                            });
                        }
                    }
                },
            };
        }

        //编辑 /删除 
        toggleEditable = (record, num) => {
            if (num == '1') {
                this.child.showModal(record, num)
            } else {
                let datas = {}
                datas = {
                    params: [{
                        updateUserID: JSON.parse(sessionStorage.userData).userID || '',
                        ID: record.ID,
                    }],
                }
                $http.post('urlS', this, {
                    code: '01040131',
                    data: datas,
                    success: function (res) {
                        if (+res.errorCode === 0) {
                            message.success('删除成功');
                            this.getFindDate()
                        }
                    }
                })
            }
        }

        //获取费用类别
        getFeeType = () => {
            let data = {
                params: [{

                }],
            }
            $http.post('urlS', this, {
                code: '01040130',
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        this.setState({
                            feeArr: res.result.data
                        })
                    }
                }
            })
        }

        //获取房间类型
        getRoomType = () => {
            let data = {
                params: [{
                    roomTypeFlag: 1
                }],
            }
            $http.post('urlS', this, {
                code: '01040022',
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        this.setState({
                            roomArr: res.roomType
                        })
                    }
                }
            })
        }

        render() {
            const { getFieldDecorator } = this.props.form;
            const { searchLoading, columns, totalWidth } = this.state;
            //医院
            let hosOp = []
            this.state.hospArr && this.state.hospArr.map((item) => {
                hosOp.push(<Option key={item.id} value={String(item.id)}>{item.descripts}</Option>)
            })
            //床位费类别
            let feeOp = []
            this.state.feeArr && this.state.feeArr.map((item) => {
                feeOp.push(<Option key={item.id} value={String(item.id)}>{item.descripts}</Option>)
            })
            //房间类型
            let roomOp = []
            this.state.roomArr && this.state.roomArr.map((item) => {
                roomOp.push(<Option key={item.id} value={String(item.id)}>{item.descripts}</Option>)
            })

            return (
                <div style={{ padding: '12px 24px' }} className="bedDom">
                    <div className="department-header">
                        <Form>
                            <Row gutter={60} style={{ margin: '0' }}>
                                <Col span={4} style={paddRightCol}>
                                    <FormItem {...formItemLayoutType} label="医院">
                                        {getFieldDecorator('hospId', {
                                            initialValue: undefined,
                                            rules: [{ required: false, message: '' }],
                                        })(
                                            <Select
                                                allowClear
                                            >
                                                {hosOp}
                                            </Select>
                                        )}
                                    </FormItem>
                                </Col>
                                <Col span={5} style={paddRightCol}>
                                    <FormItem {...formItemLayoutType} label='房间类型'>
                                        {getFieldDecorator('getRoom', {
                                            initialValue: undefined,
                                            rules: [{ required: false, message: '' }],
                                        })(
                                            <Select
                                                allowClear
                                            >
                                                {roomOp}
                                            </Select>
                                        )}
                                    </FormItem>
                                </Col>
                                <Col span={5} style={paddRightCol}>
                                    <FormItem {...formItemLayoutType} label='床位费类别'>
                                        {getFieldDecorator('getBed', {
                                            initialValue: undefined,
                                            rules: [{ required: false, message: '' }],
                                        })(
                                            <Select
                                                allowClear
                                                onChange={this.findData}
                                            >
                                                {feeOp}
                                            </Select>
                                        )}
                                    </FormItem>
                                </Col>
                                <Col span={2} style={paddRightCol}>
                                    <FormItem  {...formItemLayout}>
                                        {getFieldDecorator('posInp', {
                                            initialValue: undefined,
                                            rules: [{ required: false, message: '' }],
                                        })(
                                            <Button onClick={this.findData} loading={searchLoading} style={{ background: 'rgba(66,185,131,1)', color: '#fff' }}>查询</Button>
                                        )}
                                    </FormItem>
                                </Col>
                                <Col span={2} style={{ padding: '0px' }}>
                                    <FormItem  {...formItemLayout}>
                                        {getFieldDecorator('addNewCard', {
                                            initialValue: undefined,
                                            rules: [{ required: false, message: '' }],
                                        })(
                                            <Button onClick={this.add} style={{ background: 'rgba(66,185,131,1)', color: '#fff' }}>+房间类型关联床位费类型</Button>
                                        )}
                                    </FormItem>
                                </Col>
                            </Row>
                        </Form>
                    </div>
                    <div className="table-body-height">
                        <Table
                            scroll={{ x: totalWidth, y: store.getState().tableHeight.y + 26 }}
                            columns={columns}
                            dataSource={this.state.bedData}
                            pagination={false}
                            rowKey={record => record.key}
                            onRow={this.onClickRow}
                            rowClassName={this.setRowClassNames}
                            bordered
                            style={{ height: store.getState().tableHeight.y + 76 + 'px' }}
                        />
                        <CommonPagination size={this.state.size} page={this.state.page} current={this.state.page} total={this.state.total} search={this.state.search}
                            onShowSizeChange={this.onShowSizeChange.bind(this)} complete={true} dataSource={this.state.bedData}
                            onChange={this.onChange.bind(this)} />
                    </div>
                    <BedCostToBedTypeModal getNewData={this.getNewData} OnChildrefs={this.OnChildrefs} prioritySelectData={this.props.prioritySelectData}></BedCostToBedTypeModal>
                    <ColumnAuthoritysModel
                        clientWidth="800px"
                        compontName="RoomTypeAndBedFeeTypeAss"
                        configType="C"
                        onRef={this.onColumnRef}
                        reloadData={this.getMainTableColumns}
                    />
                </div>

            )
        }
    })
export default BedCostToBedType    